package org.teremail.store.paged;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.junit.Before;
import org.junit.Test;

public abstract class AbstractBlobFactoryTestCase {

    BlobFactory dao;
    
    @Before
    public void setUp() {
        Logger.getLogger("").setLevel(Level.FINEST);
        dao = getBlobFactory();
        dao.init();
    }
    
    public abstract BlobFactory getBlobFactory();
    
    @Test
    public void createBlob() {
        Blob b = dao.createBlob();
        assertNotNull("ID is null", b.getId());
        assertEquals("Length is not zero", 0, b.getLength());
        
        Blob b2 = dao.getBlob(b.getId());
        assertNotNull("Unable to find blob", b2);
    }
    
    @Test
    public void addPage() {
        Blob b = dao.createBlob();
        
        byte[] page1 = new byte[1024];
        page1[0] = 'a';
        page1[1] = 'b';
        page1[2] = 'c';
        
        b.addPage(page1);
        b.addPage(new byte[] { 'd', 'e', 'f' });
        
        assertEquals(1027, b.getLength());
        assertEquals(2, b.getNumPages());
        
        assertEquals((byte) 'e', b.getPage(1)[1]);
    }
    
    @Test
    public void getLastPage() {
        Blob b = dao.createBlob();
        
        byte[] page1 = new byte[1024];
        page1[0] = 'a';
        page1[1] = 'b';
        page1[2] = 'c';
        
        b.addPage(page1);
        b.addPage(new byte[] { 'd', 'e', 'f' });
        
        assertEquals(1027, b.getLength());
        assertEquals(2, b.getNumPages());
        
        assertEquals((byte) 'd', b.getLastPage()[0]);
        assertEquals((byte) 'e', b.getLastPage()[1]);
        assertEquals((byte) 'f', b.getLastPage()[2]);
    }
    
    @Test
    public void replaceLastPage() {
        Blob b = dao.createBlob();
        
        byte[] page1 = new byte[1024];
        page1[0] = 'a';
        page1[1] = 'b';
        page1[2] = 'c';
        
        b.addPage(page1);
        b.addPage(new byte[] { 'd', 'e', 'f' });
        
        assertEquals(1027, b.getLength());
        assertEquals(2, b.getNumPages());
        
        assertEquals((byte) 'd', b.getLastPage()[0]);
        assertEquals((byte) 'e', b.getLastPage()[1]);
        assertEquals((byte) 'f', b.getLastPage()[2]);
        
        byte[] lastPage = { 'd', 'e', 'f', 'x', 'y', 'z' };
        b.replaceLastPage(lastPage);
        
        byte[] result = b.getLastPage();
        assertEquals(lastPage.length, result.length);
        assertTrue("Data is not equal", Arrays.equals(lastPage, result));
    }
    
    @Test
    public void initialise() {
        dao.init();
    }
    
}
